package com.jumi.microservice.order.pipeline;

import com.jumi.microservice.order.context.TransHandlerContext;
import com.jumi.microservice.order.handler.TransHandler;

/**
 * @author Dirk
 * @Date 2020-08-04 17:34
 */
public class DefaultTransPipeline implements TransPipeline {

    /**
     * 起始节点
     */
    private final TransHandlerNode head = new TransHandlerNode();

    /**
     * 末尾节点
     */
    private TransHandlerNode tail;

    private TransHandlerContext context = null;


    public DefaultTransPipeline(TransHandlerContext context) {
        this.context = context;
        tail = head;
    }

    @Override
    public void addFirst(TransHandler... handlers) {
        TransHandlerNode pre = head.getNext();
        for (TransHandler handler : handlers) {
            if (handler == null) {
                continue;
            }
            TransHandlerNode node = new TransHandlerNode();
            node.setHandler(handler);
            node.setNext(pre);
            pre = node;
        }
        head.setNext(pre);
    }

    @Override
    public void addLast(TransHandler... handlers) {
        TransHandlerNode next = tail;
        for (TransHandler handler : handlers) {
            if (handler == null) {
                continue;
            }
            TransHandlerNode node = new TransHandlerNode();
            node.setHandler(handler);
            next.setNext(node);
            next = node;
        }
        tail = next;
    }


    @Override
    public <T extends TransHandlerContext> T getContext() {
        return (T) context;
    }

    public void setContext(TransHandlerContext context) {
        this.context = context;
    }

    @Override
    public void start() {
        head.getNext().exec(getContext());
    }

    @Override
    public void shutdown() {

    }
}
